//
//  TDAppCenterViewController.m
//  TFB
//
//  Created by yull on 15/8/14.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDAppCenterViewController.h"
#import "KDCycleBannerView.h"
#import "TDAppCenterCell.h"
#import "TDDynamicImg.h"
#import "TDTransactionQueryViewController.h"
#import "TDShoukuanViewController.h"
#import "TDNotificationViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import "TDQuickQukuanViewController.h"

#define Identifier  @"AppCenterIdentifier"

@interface TDAppCenterViewController () <KDCycleBannerViewDataSource, KDCycleBannerViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) KDCycleBannerView *bannerView;
@property (nonatomic, strong) NSMutableArray *bannerSource;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *titleArray;

@end

@implementation TDAppCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = APPNAME;
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.bannerSource = [NSMutableArray array];
    self.imageArray = @[@"ac_shoukuan", @"ac_chaxun", @"ac_withdraw", @"ac_xiaoxi", @"ac_fenxiang"];
    self.titleArray = @[@"交易收款", @"交易查询", @"快速提款", @"信息公告", @"软件分享"];
    
    [self initSubviews];
    [self initData];
}

- (void)initSubviews
{
    KDCycleBannerView *bannerView = [[KDCycleBannerView alloc] initWithFrame:CGRectMake(0, 0, SVFS.width, 120)];
    bannerView.autoPlayTimeInterval = 5;
    bannerView.datasource = self;
    bannerView.delegate = self;
    bannerView.continuous = YES;
    [self.view addSubview:bannerView];
    self.bannerView = bannerView;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width / 2, [UIScreen mainScreen].bounds.size.width / 2 - 20);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(bannerView.frame), SVFS.width, SVFS.height - CGRectGetMaxY(bannerView.frame)) collectionViewLayout:flowLayout];
    collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.pagingEnabled = YES;
    [collectionView registerClass:[TDAppCenterCell class] forCellWithReuseIdentifier:Identifier];
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.collectionView reloadData];
}

- (void)initData
{
    [self.bannerSource addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:INDEX_BANNER]];
    
    [TDHttpEngine requestForIndexPageBannerSourceWithCustMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] custId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] complete:^(BOOL succeed, NSString *msg, id req_body) {
        if (succeed) {
            NSArray *dataArray = [req_body objectForKey:@"imgList"];
            
            if (dataArray.count) {
                [self.bannerSource removeAllObjects];
            }
            
            for (int i = 0; i < dataArray.count; i ++) {
                TDDynamicImg *dynamicImg = [[TDDynamicImg alloc] initWithDictionary:dataArray[i]];
                [self.bannerSource addObject:dynamicImg.fileUrl];
            }
            
            if (self.bannerSource.count) {
                [[NSUserDefaults standardUserDefaults] setObject:self.bannerSource forKey:INDEX_BANNER];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            
            [self.bannerView reloadDataWithCompleteBlock:nil];
        }
    }];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [TDHttpEngine requestForGetCustInfWithCustMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] custId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] complete:^(BOOL succeed, NSString *msg, NSString *cod, TDUser *user) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (succeed) {
            
        }
        else
        {
            [self.view makeToast:msg duration:2.0f position:@"center"];
        }
    }];
    
    NSString *noticeLastId = [[NSUserDefaults standardUserDefaults] objectForKey:@"NOTICELASTID"];
    if (!noticeLastId.length) {
        noticeLastId = @"0";
    }
    [TDHttpEngine requestFor_GETLATESTNOTICE_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] lastId:noticeLastId complete:^(BOOL succeed, NSString *msg, id reqBody) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (succeed) {
            NSDictionary *INFO = [reqBody objectForKey:@"INFO"];
            NSInteger count = [[INFO objectForKey:@"count"] integerValue];
            if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] != NSOrderedDescending) {
                UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
                
                [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
                
                UIApplication *app = [UIApplication sharedApplication];
                // 应用程序右上角数字
                app.applicationIconBadgeNumber = count;
                
                [[NSUserDefaults standardUserDefaults] setObject:@(count) forKey:@"IconBadgeNumber"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [self.collectionView reloadData];
            } else {
                
                UIApplication *app = [UIApplication sharedApplication];
                
                [app registerForRemoteNotificationTypes:
                 (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                            UIRemoteNotificationTypeBadge |
                                            UIRemoteNotificationTypeSound)];
                
                // 应用程序右上角数字
                app.applicationIconBadgeNumber = count;
                
                [[NSUserDefaults standardUserDefaults] setObject:@(count) forKey:@"IconBadgeNumber"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [self.collectionView reloadData];
            }
            
        }
        else
        {
            [self.view makeToast:msg duration:2.0f position:@"center"];
        }
    }];
}

- (void)showShare
{
//    __weak typeof(self) theController = self;
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
#ifdef SHARE_URL_NEED_ID
    NSString *shareText = [NSString stringWithFormat:@"我用的“%@”手机快捷支付非常好用，现在推荐给你使用，快打开网址下载吧，%@%@", APPNAME, SHARE_URL, [[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]];
#else
    NSString *shareText = [NSString stringWithFormat:@"我用的“%@”手机快捷支付非常好用，现在推荐给你使用，快打开网址下载吧，%@", APPNAME, SHARE_URL];
#endif
    [shareParams SSDKSetupShareParamsByText:shareText
                                     images:nil
                                        url:nil
                                      title:nil
                                       type:SSDKContentTypeText];
    
    
    [ShareSDK showShareActionSheet:self.view
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                           
                       case SSDKResponseStateBegin:
                       {
                           [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           if (platformType == SSDKPlatformTypeSMS && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、短信应用没有设置帐号；2、设备不支持短信应用；3、短信应用在iOS 7以上才能发送带附件的短信。"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           break;
                       }
                       default:
                           break;
                   }
                   
                   if (state != SSDKResponseStateBegin)
                   {
                       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                   }
                   
               }];
    
}

#pragma mark - KDCycleBannerViewDataSource, KDCycleBannerViewDelegate
- (NSArray *)numberOfKDCycleBannerView:(KDCycleBannerView *)bannerView
{
    return self.bannerSource;
}

- (UIViewContentMode)contentModeForImageIndex:(NSUInteger)index
{
    return UIViewContentModeScaleAspectFill;
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TDAppCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Identifier forIndexPath:indexPath];
    
    cell.imageView.image = [UIImage imageNamed:self.imageArray[indexPath.row]];
    cell.titleLabel.text = self.titleArray[indexPath.row];
    
    if (indexPath.row == 3) {
        
        NSInteger count = [[[NSUserDefaults standardUserDefaults] objectForKey:@"IconBadgeNumber"] integerValue];
        cell.badgeView.badgeText = count ? [NSString stringWithFormat:@"%ld", (long)count] : nil;
    } else {
        cell.badgeView.badgeText = nil;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        if ([[TDUser defaultUser].cardBundingStatus isEqualToString:@"1"]) {
            [self.view makeToast:@"绑定银行卡正在审核中" duration:2.0f position:@"center"];
            return;
        } else if (![[TDUser defaultUser].cardBundingStatus isEqualToString:@"2"]) {
            [self.view makeToast:@"还未绑定银行卡" duration:2.0f position:@"center"];
            return;
        }
        
        if ([[TDUser defaultUser].custStatus isEqualToString:@"1"]) {
            [self.view makeToast:@"实名认证正在审核中" duration:2.0f position:@"center"];
            return;
        } else if (![[TDUser defaultUser].custStatus isEqualToString:@"2"]) {
            [self.view makeToast:@"还未实名认证" duration:2.0f position:@"center"];
            return;
        }
        
        TDShoukuanViewController *controller = [[TDShoukuanViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    } else if (indexPath.row == 1) {
        TDTransactionQueryViewController *controller = [[TDTransactionQueryViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    } else if (indexPath.row == 2) {
        if ([[TDUser defaultUser].cardBundingStatus isEqualToString:@"1"]) {
            [self.view makeToast:@"绑定银行卡正在审核中" duration:2.0f position:@"center"];
            return;
        } else if (![[TDUser defaultUser].cardBundingStatus isEqualToString:@"2"]) {
            [self.view makeToast:@"还未绑定银行卡" duration:2.0f position:@"center"];
            return;
        }
        
        if ([[TDUser defaultUser].custStatus isEqualToString:@"1"]) {
            [self.view makeToast:@"实名认证正在审核中" duration:2.0f position:@"center"];
            return;
        } else if (![[TDUser defaultUser].custStatus isEqualToString:@"2"]) {
            [self.view makeToast:@"还未实名认证" duration:2.0f position:@"center"];
            return;
        }
        
        TDQuickQukuanViewController *controller = [[TDQuickQukuanViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if (indexPath.row == 3) {
        TDNotificationViewController *controller = [[TDNotificationViewController alloc] initWithStyle:UITableViewStylePlain];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [self showShare];
    }
}

@end
